package com.hx.shiro.controller;

import com.hx.shiro.vo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    @RequestMapping(value = "/subLogin", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String subLogin(User user) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),
            user.getPassword());
        try {
            // 自动登录
            token.setRememberMe(user.isRememberMe());
            subject.login(token);
        } catch (AuthenticationException authenException) {
            return authenException.getMessage();
        }

        if(subject.hasRole("admin")) {
            return "有admin权限";
        }

        return "无admin权限";
    }

    //通过注解设置角色权限为admin才可访问
    @RequiresRoles("admin")
    @RequestMapping(value = "/testRole_admin", method = RequestMethod.GET)
    @ResponseBody
    public String testRole_admin() {
        return "test role admin success";
    }

    @RequiresPermissions("user:delete")
    @RequestMapping(value = "/testPer_delete", method = RequestMethod.GET)
    @ResponseBody
    public String testPer_user_delete() {
        return "testPer_user_delete success";
    }

    @RequiresPermissions("user:update")
    @RequestMapping(value = "/testPer_update", method = RequestMethod.GET)
    @ResponseBody
    public String testPer_user_update() {
        return "testPer_user_update success";
    }

    /**
     * 通过在service.xml配置访问权限
     */
    @RequestMapping(value = "/testRole", method = RequestMethod.GET)
    @ResponseBody
    public String testRole() {
        return "test role success";
    }

    @RequestMapping(value = "/testRoles", method = RequestMethod.GET)
    @ResponseBody
    public String testRoles() {
        return "test roles success";
    }

    @RequestMapping(value = "/testPerms", method = RequestMethod.GET)
    @ResponseBody
    public String testPerms() {
        return "test testPerms success";
    }

    @RequestMapping(value = "/testPerms1", method = RequestMethod.GET)
    @ResponseBody
    public String testPerms1() {
        return "test testPerms1 success";
    }

}